<template>
  <div class="comment-management-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form
        :model="searchForm"
        class="search-form"
        :inline="true"
      >
        <el-form-item label="帖子ID">
          <el-input
            v-model="searchForm.postId"
            placeholder="请输入帖子ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="父评论ID">
          <el-input
            v-model="searchForm.parentId"
            placeholder="请输入父评论ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="评论状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 140px"
          >
            <el-option
              label="有效"
              value="valid"
            />
            <el-option
              label="无效"
              value="invalid"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="pagedTableData"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="postComment.commentId"
          label="评论ID"
          width="100"
          align="center"
        />

        <el-table-column
          label="评论用户"
          width="180"
          align="center"
        >
          <template #default="{row}">
            <div
              v-if="row.commentUser"
              class="user-info"
            >
              <el-avatar
                :size="40"
                :src="row.commentUser.avatar || defaultAvatar"
              />
              <div class="user-id">
                <div class="user-id">
                  <div class="user-name">
                    {{ row.commentUser.nickname }}
                  </div>
                </div>
                ID: {{ row.postComment.accountId }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          label="被回复用户"
          width="180"
          align="center"
        >
          <template #default="{row}">
            <div
              v-if="row.postComment.toUserId > 0"
              class="user-info"
            >
              <el-avatar
                :size="40"
                :src="row.repliedUser.avatar || defaultAvatar"
              />
              <div class="user-id">
                <div class="user-name">
                  {{ row.repliedUser.nickname }}
                </div>
                ID: {{ row.postComment.toUserId }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="postComment.postId"
          label="帖子ID"
          width="100"
          align="center"
        />

        <el-table-column
          label="评论内容"
          min-width="200"
          align="center"
        >
          <template #default="{row}">
            <div class="content-preview">
              <div class="text-content">
                {{ row.postComment.content }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="status"
          label="评论状态"
          width="100"
          align="center"
        >
          <template #default="{row}">
            <el-tag :type="row.postComment.isDelete ? 'danger' : 'success'">
              {{ row.postComment.isDelete ? '无效' : '有效' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="父评论内容"
          min-width="200"
          align="center"
        >
          <template #default="{row}">
            <div
              v-if="row.parentContent"
              class="content-preview"
            >
              <div class="text-content">
                {{ row.parentContent }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="postComment.commentTime"
          label="评论时间"
          width="160"
          align="center"
        />

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          width="220"
          fixed="right"
          align="center"
        >
          <template #default="{row}">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="handleProcess(row)"
              >
                处理
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="handleDetail(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="custom-pagination left-pagination">
      <div class="pagination-left">
        <span class="total-info">共 {{ filteredData.length }} 条记录</span>

        <el-pagination
          :current-page.sync="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="filteredData.length"
          :pager-count="5"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />

        <div class="page-size-select">
          <span>每页</span>
          <el-select
            v-model="pagination.pageSize"
            size="mini"
            style="width: 60px"
            @change="handlePageSizeChange"
          >
            <el-option
              label="6"
              :value="6"
            />
            <el-option
              label="10"
              :value="10"
            />
            <el-option
              label="20"
              :value="20"
            />
          </el-select>
          <span>条</span>
        </div>

        <div class="page-jump">
          <span>前往</span>
          <el-input
            v-model.number="jumpPage"
            size="mini"
            style="width: 50px"
            @keyup.enter.native="handleJumpPage"
          />
          <span>页</span>
        </div>
      </div>
    </div>

    <!-- 处理对话框 -->
    <el-dialog
      title="评论处理"
      :visible.sync="processDialogVisible"
      width="50%"
      :modal="false"
    >
      <div
        v-if="currentComment"
        class="process-content"
      >
        <el-form label-width="100px">
          <el-form-item label="评论内容">
            <el-input
              v-model="currentComment.content"
              type="textarea"
              :rows="3"
              readonly
            />
          </el-form-item>

          <el-form-item label="评论状态">
            <el-radio-group v-model="currentComment.status">
              <el-radio label="valid">
                有效
              </el-radio>
              <el-radio label="invalid">
                无效
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="processDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmProcess"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="评论详情"
      :visible.sync="detailDialogVisible"
      width="50%"
      top="5vh"
      :modal="false"
      :close-on-click-modal="false"
    >
      <div
        v-if="currentComment"
        class="detail-content"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="comment-content">
              <div class="user-info">
                <el-avatar
                  :size="50"
                  :src="currentComment.user.avatar || defaultAvatar"
                />
                <div class="user-meta">
                  <div class="user-id">
                    用户ID: {{ currentComment.user.id }}
                  </div>
                  <div class="comment-time">
                    {{ currentComment.createTime }}
                  </div>
                </div>
              </div>

              <div class="content-box">
                <h3>评论内容</h3>
                <pre style="white-space: pre-wrap;">{{ currentComment.content }}</pre>
              </div>

              <div
                v-if="currentComment.repliedUser"
                class="content-box"
              >
                <h3>回复用户</h3>
                <div class="user-info">
                  <el-avatar
                    :size="40"
                    :src="currentComment.repliedUser.avatar || defaultAvatar"
                  />
                  <div class="user-meta">
                    <div class="user-id">
                      ID: {{ currentComment.repliedUser.id }}
                    </div>
                  </div>
                </div>
              </div>

              <div
                v-if="currentComment.parentContent"
                class="content-box"
              >
                <h3>父评论内容</h3>
                <pre style="white-space: pre-wrap;">{{ currentComment.parentContent }}</pre>
              </div>
            </div>
          </el-col>

          <el-col :span="8">
            <div class="comment-meta">
              <el-descriptions
                :column="1"
                border
              >
                <el-descriptions-item label="评论ID">
                  {{ currentComment.id }}
                </el-descriptions-item>
                <el-descriptions-item label="所属帖子">
                  {{ currentComment.postId }}
                </el-descriptions-item>
                <el-descriptions-item label="评论状态">
                  <el-tag :type="currentComment.status === 'valid' ? 'success' : 'danger'">
                    {{ currentComment.status === 'valid' ? '有效' : '无效' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import $ from 'jquery'

export default {
  name: 'CommentManagement',
  data () {
    return {
      searchForm: {
        postId: '',
        userId: '',
        parentId: '',
        status: ''
      },
      tableData: [
        // {
        //   id: '1001',
        //   user: { id: '2001', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' },
        //   repliedUser: { id: '2002', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
        //   postId: '3001',
        //   content: '这个帖子写得真好，学到了很多知识！',
        //   status: 'valid',
        //   parentContent: '我也觉得这个帖子很有价值',
        //   createTime: '2023-05-10 14:30:22'
        // }
      ],
      filteredData: [],
      pagination: {
        currentPage: 1,
        pageSize: 6
      },
      jumpPage: 1,
      processDialogVisible: false,
      detailDialogVisible: false,
      currentComment: {
        user: {},
        repliedUser: null
      },
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      loading: false
    }
  },
  computed: {
    pagedTableData () {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredData.slice(start, end)
    },
    totalPages () {
      return Math.ceil(this.filteredData.length / this.pagination.pageSize)
    }
  },
  created () {
    // this.filteredData = [...this.tableData]
    this.fetchComments()
  },
  methods: {
    // 获取评论列表
    fetchComments () {
      this.loading = true
      $.ajax({
        url: 'http://localhost:3000/api/getAllComments',
        type: 'GET',
        dataType: 'json',
        success: (response) => {
          if (response.code === 200) {
            console.log(response.data)
            this.tableData = response.data
            this.filteredData = [...this.tableData]
          } else {
            this.$message.error(response.message || '获取评论列表失败')
          }
        },
        error: (xhr, status, error) => {
          this.$message.error('请求评论列表失败: ' + error)
        },
        complete: () => {
          this.loading = false
        }
      })
    },

    // 搜索评论
    handleSearch () {
      this.loading = true
      const params = {
        postId: this.searchForm.postId,
        userId: this.searchForm.userId,
        parentId: this.searchForm.parentId,
        status: this.searchForm.status,
        page: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }

      $.ajax({
        url: '/api/comments/search',
        type: 'GET',
        data: params,
        dataType: 'json',
        success: (response) => {
          if (response.code === 200) {
            this.filteredData = response.data
            this.pagination.currentPage = 1
            this.jumpPage = 1
          } else {
            this.$message.error(response.message || '搜索评论失败')
          }
        },
        error: (xhr, status, error) => {
          this.$message.error('搜索评论请求失败: ' + error)
        },
        complete: () => {
          this.loading = false
        }
      })
    },

    resetSearch () {
      this.searchForm = {
        postId: '',
        userId: '',
        parentId: '',
        status: ''
      }
      this.fetchComments()
      this.pagination.currentPage = 1
      this.jumpPage = 1
    },

    handlePageSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.jumpPage = 1
    },

    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.jumpPage = val
    },

    handleJumpPage () {
      const pageNum = Number(this.jumpPage)
      if (isNaN(pageNum) || pageNum < 1 || pageNum > this.totalPages) {
        this.$message.warning(`请输入1-${this.totalPages}之间的页码`)
        this.jumpPage = this.pagination.currentPage
        return
      }
      this.pagination.currentPage = pageNum
    },

    handleProcess (row) {
      this.currentComment = {
        ...JSON.parse(JSON.stringify(row)),
        user: row.user || { id: '', avatar: this.defaultAvatar },
        repliedUser: row.repliedUser || null
      }
      this.processDialogVisible = true
    },

    handleDetail (row) {
      this.currentComment = {
        ...JSON.parse(JSON.stringify(row)),
        user: row.user || { id: '', avatar: this.defaultAvatar },
        repliedUser: row.repliedUser || null
      }
      this.detailDialogVisible = true
    },

    // 删除评论
    handleDelete (row) {
      this.$confirm('确定要删除这条评论吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        $.ajax({
          url: `/api/comments/${row.id}`,
          type: 'DELETE',
          dataType: 'json',
          success: (response) => {
            if (response.code === 200) {
              this.$message.success('删除评论成功')
              this.fetchComments() // 重新加载数据
            } else {
              this.$message.error(response.message || '删除评论失败')
            }
          },
          error: (xhr, status, error) => {
            this.$message.error('删除评论请求失败: ' + error)
          },
          complete: () => {
            this.loading = false
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 更新评论状态
    confirmProcess () {
      this.loading = true
      $.ajax({
        url: `/api/comments/${this.currentComment.id}/status`,
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
          status: this.currentComment.status
        }),
        dataType: 'json',
        success: (response) => {
          if (response.code === 200) {
            this.$message.success('评论状态更新成功')
            this.fetchComments() // 重新加载数据
            this.processDialogVisible = false
          } else {
            this.$message.error(response.message || '更新评论状态失败')
          }
        },
        error: (xhr, status, error) => {
          this.$message.error('更新评论状态请求失败: ' + error)
        },
        complete: () => {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.comment-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.table-area {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 5px 0;
}

.user-info .user-id {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.content-preview {
  max-height: 100px;
  overflow: hidden;
  padding: 5px 0;
}

.content-preview .text-content {
  font-size: 13px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-wrap;
}

.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-buttons .el-button {
  flex: 1;
  min-width: 60px;
  padding: 7px 10px;
}

.custom-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.total-info {
  font-size: 13px;
  color: #606266;
  margin-right: 10px;
}

.page-jump {
  font-size: 13px;
  color: #606266;
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.detail-content {
  padding: 10px;
}

.comment-content {
  padding-right: 20px;
}

.comment-content h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 18px;
}

.comment-content .user-meta {
  margin-left: 10px;
}

.comment-content .user-id {
  font-size: 14px;
  font-weight: bold;
}

.comment-content .comment-time {
  font-size: 12px;
  color: #909399;
}

.content-box {
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-wrap;
  font-size: 14px;
}

@media (max-width: 1200px) {
  .search-form .el-form-item {
    margin-bottom: 10px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

.user-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.user-meta {
  margin-left: 10px;
  text-align: left;
}

.user-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.user-id {
  font-size: 12px;
  color: #888;
}
</style>
